package com.cebbank.yyi.springbootapp.poi;

import cn.hutool.core.util.StrUtil;
import com.cebbank.yyi.springbootapp.annocation.Excel;
import com.cebbank.yyi.springbootapp.annocation.Excel.Type;
import com.cebbank.yyi.springbootapp.annocation.Excels;
import com.cebbank.yyi.springbootapp.tables.ColumsBO;
import com.cebbank.yyi.springbootapp.tables.CreateTablesBO;
import com.cebbank.yyi.springbootapp.tables.ImportDataBO;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDataValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * Excel相关处理工具类
 *
 * @author yyi
 */
public class ExcelUtils<T> {

    private static final Logger log = LoggerFactory.getLogger(ExcelUtils.class);

    public static final String FORMULA_REGEX_STR = "=|-|\\+|@";

    public static final String[] FORMULA_STR = {"=", "-", "+", "@"};

    /**
     * Excel sheet最大行数，默认50000
     */
    public static final int sheetSize = 50000;

    /**
     * sheet页 Name
     */
    private List<String> sheetName;

    /**
     * 导出类型（EXPORT:导出数据；IMPORT：导入模板）
     */
    private Type type;

    /**
     * 工作薄对象
     */
    private Workbook workbook;

    /**
     * Sheet页
     */
    private final List<Sheet> sheet = new ArrayList<>();

    /**
     * 样式列表
     */
    private List<Map<String, CellStyle>> styles;

    /**
     * 操作数据列表（包含导入 导出）
     */
    private List<List<?>> list;

    /**
     * 注解列表
     */
    private List<List<Object[]>> fields;

    /**
     * 当前行号
     */
    private int rowNum;

    /**
     * 标题
     */
    private List<String> title;

    /**
     * 最大高度
     */
    private List<Short> maxHeight;

    /**
     * 合并后最后行数
     */
    private int subMergedLastRowNum = 0;

    /**
     * 合并后开始行数
     */
    private int subMergedFirstRowNum = 1;

    /**
     * 对象的子列表方法
     */
    private final List<Method> subMethod = new ArrayList<>();

    /**
     * 对象的子列表属性
     */
    private final List<List<Field>> subFields = new ArrayList<>();

    /**
     * 统计列表
     */
    public final Map<Integer, Double> statistics = new HashMap<>();

    /**
     * 数字格式
     */
    private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");

    /**
     * 实体对象
     */
    public List<Class<?>> clazz;

    /**
     * 需要排除列属性
     */
    public String[] excludeFields;

    /**
     * 构造方法 支持传入实体类对象
     **/
    public ExcelUtils(List<Class<?>> clazz) {
        this.clazz = clazz;
    }


    /***
     * Excel操作需要初始化准备的内容
     * list 数据
     * sheetName sheet页名称
     * 文件标题
     * 操作类型，导入还是导出
     * **/
    public void init(List<List<? extends Object>> list, List<String> sheetName, List<String> title, Type type) {
        if (list == null) {
            list = new ArrayList<>();
        }
        this.list = list;
        this.sheetName = sheetName;
        this.type = type;
        this.title = title;
        createExcelField();
        createWorkbook();
        createTitle();
        createSubHead();
    }

    /**
     * 创建一个工作簿
     */
    public void createWorkbook() {
        this.workbook = new SXSSFWorkbook(500);
        for (int i = 0; i < sheetName.size(); i++) {
            sheet.add(workbook.createSheet());
            workbook.setSheetName(i, sheetName.get(i));
            styles = createStyles(workbook);
        }

    }


    /**
     * 合计统计信息
     */
    private void addStatisticsData(Integer index, String text, Excel entity) {
        if (entity != null && entity.isStatistics()) {
            Double temp = 0D;
            if (!statistics.containsKey(index)) {
                statistics.put(index, temp);
            }
            try {
                temp = Double.valueOf(text);
            } catch (NumberFormatException e) {
            }
            statistics.put(index, statistics.get(index) + temp);
        }
    }

    /**
     * 导出Excel创建Excel表格的第一行
     */
    public void createTitle() {
        for (int i = 0; i < title.size(); i++) {
            if (StrUtil.isNotEmpty(title.get(i))) {
                subMergedFirstRowNum++;
                subMergedLastRowNum++;
                int titleLastCol = this.fields.get(i).size() - 1;
                if (isSubList(i)) {
                    titleLastCol = titleLastCol + subFields.get(i).size() - 1;
                }
                Row titleRow = sheet.get(i).createRow(rowNum == 0 ? rowNum++ : 0);
                titleRow.setHeightInPoints(30);
                Cell titleCell = titleRow.createCell(0);
                titleCell.setCellStyle(styles.get(i).get("title"));
                titleCell.setCellValue(title.get(i));
                sheet.get(i).addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), titleLastCol));
            }
        }

    }

    /**
     * 得到所有定义字段
     */
    private void createExcelField() {
        this.fields = getFields();
        //this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList());
        //this.fields = fields.stream().filter(it -> it.sort(Comparator.comparing(objects -> ((Excel) objects[1]).sort()))).collect(Collectors.toList());
        maxHeight = getRowHeight();
    }

    /**
     * 创建对象的子列表名称
     */
    public void createSubHead() {
        for (int i = 0; i < sheetName.size(); i++) {
            if (isSubList(i)) {
                subMergedFirstRowNum++;
                subMergedLastRowNum++;
                Row subRow = sheet.get(i).createRow(rowNum);
                int excelNum = 0;
                for (Object[] objects : fields.get(i)) {
                    Excel attr = (Excel) objects[1];
                    Cell headCell1 = subRow.createCell(excelNum);
                    headCell1.setCellValue(attr.name());
                    headCell1.setCellStyle(styles.get(i).get(StrUtil.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
                    excelNum++;
                }
                int headFirstRow = excelNum - 1;
                int headLastRow = headFirstRow + subFields.get(i).size() - 1;
                if (headLastRow > headFirstRow) {
                    sheet.get(i).addMergedRegion(new CellRangeAddress(rowNum, rowNum, headFirstRow, headLastRow));
                }
                rowNum++;
            }
        }

    }

    /**
     * 对excel表单默认第一个索引名转换成list
     *
     * @param is 输入流
     * @return 转换后集合
     */
    public List<T> importExcel(InputStream is) throws Exception {
        return importExcel(is, 0);
    }

    /**
     * 对excel表单指定表格索引名转换成list
     *
     * @param titleNum 标题占用行数
     * @param is       输入流
     * @return 转换后集合
     */
    public List<List<Object>> importExcels(InputStream is, int titleNum) throws Exception {
        this.type = Type.IMPORT;
        this.workbook = WorkbookFactory.create(is);
        List<Object> list = new ArrayList<>();
        List<List<Object>> result = new ArrayList<>();
        // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
        // StrUtil.isNotEmpty(sheetName) ? workbook.getSheet(sheetName) : workbook.getSheetAt(0)
        Sheet sheet;
        int numberOfSheets = workbook.getNumberOfSheets();
        for (int j = 0; j < numberOfSheets; j++) {
            sheet = workbook.getSheetAt(j);
            int rows = sheet.getLastRowNum();
            if (rows > 0) {
                // 定义一个map用于存放excel列的序号和field.
                Map<String, Integer> cellMap = new HashMap<>();
                // 获取表头
                Row heard = sheet.getRow(titleNum);
                for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
                    Cell cell = heard.getCell(i);
                    if (cell != null) {
                        String value = this.getCellValue(heard, i).toString();
                        cellMap.put(value, i);
                    } else {
                        cellMap.put(null, i);
                    }
                }
                // 有数据时才处理 得到类的所有field.
                List<List<Object[]>> fields = this.getFields();
                Map<Integer, Object[]> fieldsMap = new HashMap<>();
                for (Object[] objects : fields.get(j)) {
                    Excel attr = (Excel) objects[1];
                    Integer column = cellMap.get(attr.name());
                    if (column != null) {
                        fieldsMap.put(column, objects);
                    }
                }
                for (int i = titleNum + 1; i <= rows; i++) {
                    // 从第2行开始取数据,默认第一行是表头.
                    Row row = sheet.getRow(i);
                    // 判断当前行是否是空行
                    if (isRowEmpty(row)) {
                        continue;
                    }
                    Object entity = null;
                    for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet()) {
                        Object val = this.getCellValue(row, entry.getKey());

                        // 如果不存在实例则新建.
                        entity = (entity == null ? clazz.get(j).newInstance() : entity);
                        // 从map中得到对应列的field.
                        Field field = (Field) entry.getValue()[0];
                        Excel attr = (Excel) entry.getValue()[1];
                        // 取得类型,并根据对象类型设置值.
                        Class<?> fieldType = field.getType();
                        if (String.class == fieldType) {
                            String s = Convert.toStr(val);
                            if (StrUtil.endWith(s, ".0")) {
                                val = StringUtils.substringBefore(s, ".0");
                            } else {
                                String dateFormat = field.getAnnotation(Excel.class).dateFormat();
                                if (StrUtil.isNotEmpty(dateFormat)) {
                                    val = parseDateToStr(dateFormat, val);
                                } else {
                                    val = Convert.toStr(val);
                                }
                            }
                        } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StrUtil.isNumeric(Convert.toStr(val))) {
                            val = Convert.toInt(val);
                        } else if ((Long.TYPE == fieldType || Long.class == fieldType) && StrUtil.isNumeric(Convert.toStr(val))) {
                            val = Convert.toLong(val);
                        } else if (Double.TYPE == fieldType || Double.class == fieldType) {
                            val = Convert.toDouble(val);
                        } else if (Float.TYPE == fieldType || Float.class == fieldType) {
                            val = Convert.toFloat(val);
                        } else if (BigDecimal.class == fieldType) {
                            val = Convert.toBigDecimal(val);
                        } else if (Date.class == fieldType) {
                            if (val instanceof String) {
                                val = DateUtils.parseDate(val.toString());
                            } else if (val instanceof Double) {
                                val = DateUtil.getJavaDate((Double) val);
                            }
                        } else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
                            val = Convert.toBool(val, false);
                        }
                        String propertyName = field.getName();
                        if (StrUtil.isNotEmpty(attr.targetAttr())) {
                            propertyName = field.getName() + "." + attr.targetAttr();
                        } else if (StrUtil.isNotEmpty(attr.readConverterExp())) {
                            val = PoiHandler.reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
                        } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
                            //改动
                            val = PoiHandler.dataFormatHandlerAdapter(val, attr);
                        }
                        BeanUtils.invoke(entity, propertyName, val);
                    }
                    list.add(entity);
                }
            }

            result.add(list);
        }

        return result;
    }

    public List<ImportDataBO> importsExcels(Workbook workbook, int titleNum, List<CreateTablesBO> headers) throws Exception {
        this.type = Type.IMPORT;
        this.workbook = workbook;
        List<ImportDataBO> result = new ArrayList<>();
        // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
        // StrUtil.isNotEmpty(sheetName) ? workbook.getSheet(sheetName) : workbook.getSheetAt(0)
        Sheet sheet;
        int numberOfSheets = workbook.getNumberOfSheets();
        for (int j = 0; j < numberOfSheets; j++) {
            ImportDataBO importDataBO = new ImportDataBO();
            //当前sheet页所有的数据集合
            List<List<Object>> lists = new ArrayList<>();
            //当前sheet页面对应的表信息
            if (headers != null && !headers.isEmpty()) {
                importDataBO.setTableInfo(headers.get(j));
            }
            sheet = workbook.getSheetAt(j);
            int rows = sheet.getLastRowNum();
            if (rows > 0) {
                //读取表头
                Row headerRow = sheet.getRow(1);
                List<String> columnHeaders = new ArrayList<>();
                for (int m = 0; m < headerRow.getLastCellNum(); m++) {
                    String headerValue = this.getCellValue(headerRow, m).toString();
                    columnHeaders.add(headerValue);
                }
                importDataBO.setHeaders(columnHeaders);
                for (int i = titleNum + 1; i <= rows; i++) {
                    List<Object> list = new ArrayList<>();

                    // 从第2行开始取数据,默认第一行是表头.
                    Row row = sheet.getRow(i);
                    // 判断当前行是否是空行
                    if (isRowEmpty(row)) {
                        continue;
                    }
                    for (int m = 0; m < row.getLastCellNum(); m++) {
                        Object value = this.getCellValue(row, m);
                        list.add(value);
                    }
                    lists.add(list);
                }
                importDataBO.setResult(lists);
            }
            result.add(importDataBO);
        }
        return result;
    }

    /**
     * 对excel表单默认第一个索引名转换成list
     *
     * @param is       输入流
     * @param titleNum 标题占用行数
     * @return 转换后集合
     */
    public List<T> importExcel(InputStream is, int titleNum) throws Exception {
        return importExcel(StrUtil.EMPTY, is, titleNum);
    }

    /**
     * 对excel表单指定表格索引名转换成list
     *
     * @param sheetName 表格索引名
     * @param titleNum  标题占用行数
     * @param is        输入流
     * @return 转换后集合
     */
    public List<T> importExcel(String sheetName, InputStream is, int titleNum) throws Exception {
        this.type = Type.IMPORT;
        this.workbook = WorkbookFactory.create(is);
        List<T> list = new ArrayList<>();
        // 如果指定sheet名,则取指定sheet中的内容 否则默认指向第1个sheet
        Sheet sheet = StrUtil.isNotEmpty(sheetName) ? workbook.getSheet(sheetName) : workbook.getSheetAt(0);
        if (sheet == null) {
            throw new IOException("文件sheet不存在");
        }

        // 获取最后一个非空行的行下标，比如总行数为n，则返回的为n-1
        int rows = sheet.getLastRowNum();

        if (rows > 0) {
            // 定义一个map用于存放excel列的序号和field.
            Map<String, Integer> cellMap = new HashMap<>();
            // 获取表头
            Row heard = sheet.getRow(titleNum);
            for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) {
                Cell cell = heard.getCell(i);
                if (cell != null) {
                    String value = this.getCellValue(heard, i).toString();
                    cellMap.put(value, i);
                } else {
                    cellMap.put(null, i);
                }
            }
            // 有数据时才处理 得到类的所有field.
            List<Object[]> fields = this.getFields().get(0);
            Map<Integer, Object[]> fieldsMap = new HashMap<>();
            for (Object[] objects : fields) {
                Excel attr = (Excel) objects[1];
                Integer column = cellMap.get(attr.name());
                if (column != null) {
                    fieldsMap.put(column, objects);
                }
            }
            for (int i = titleNum + 1; i <= rows; i++) {
                // 从第2行开始取数据,默认第一行是表头.
                Row row = sheet.getRow(i);
                // 判断当前行是否是空行
                if (isRowEmpty(row)) {
                    continue;
                }
                T entity = null;
                for (Map.Entry<Integer, Object[]> entry : fieldsMap.entrySet()) {
                    Object val = this.getCellValue(row, entry.getKey());

                    // 如果不存在实例则新建.
                      entity = (entity == null ? (T) clazz.get(0).newInstance() : entity);
                    // 从map中得到对应列的field.
                    Field field = (Field) entry.getValue()[0];
                    Excel attr = (Excel) entry.getValue()[1];
                    // 取得类型,并根据对象类型设置值.
                    Class<?> fieldType = field.getType();
                    if (String.class == fieldType) {
                        String s = Convert.toStr(val);
                        if (StrUtil.endWith(s, ".0")) {
                            val = StringUtils.substringBefore(s, ".0");
                        } else {
                            String dateFormat = field.getAnnotation(Excel.class).dateFormat();
                            if (StrUtil.isNotEmpty(dateFormat)) {
                                val = parseDateToStr(dateFormat, val);
                            } else {
                                val = Convert.toStr(val);
                            }
                        }
                    } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && StrUtil.isNumeric(Convert.toStr(val))) {
                        val = Convert.toInt(val);
                    } else if ((Long.TYPE == fieldType || Long.class == fieldType) && StrUtil.isNumeric(Convert.toStr(val))) {
                        val = Convert.toLong(val);
                    } else if (Double.TYPE == fieldType || Double.class == fieldType) {
                        val = Convert.toDouble(val);
                    } else if (Float.TYPE == fieldType || Float.class == fieldType) {
                        val = Convert.toFloat(val);
                    } else if (BigDecimal.class == fieldType) {
                        val = Convert.toBigDecimal(val);
                    } else if (Date.class == fieldType) {
                        if (val instanceof String) {
                            val = DateUtils.parseDate(val.toString());
                        } else if (val instanceof Double) {
                            val = DateUtil.getJavaDate((Double) val);
                        }
                    } else if (Boolean.TYPE == fieldType || Boolean.class == fieldType) {
                        val = Convert.toBool(val, false);
                    }
                    String propertyName = field.getName();
                    if (StrUtil.isNotEmpty(attr.targetAttr())) {
                        propertyName = field.getName() + "." + attr.targetAttr();
                    } else if (StrUtil.isNotEmpty(attr.readConverterExp())) {
                        val = PoiHandler.reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator());
                    } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
                        //改动
                        val = PoiHandler.dataFormatHandlerAdapter(val, attr);
                    }
                    BeanUtils.invoke(entity, propertyName, val);
                }
                list.add(entity);
            }
        }
        return list;
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param response  返回数据
     * @param list      导出数据集合
     * @param sheetName 工作表的名称
     * @return 结果
     */
    public void exportExcel(HttpServletResponse response, List<List<?>> list, List<String> sheetName) {
        exportExcel(response, list, sheetName, new ArrayList<>());
    }

    /**
     * 支持通过浏览器下载
     *
     * @param response  返回数据
     * @param list      导出数据集合
     * @param sheetName 工作表的名称
     * @param title     标题
     * @return 结果
     */
    public void exportExcel(HttpServletResponse response, List<List<?>> list, List<String> sheetName, List<String> title) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;fileName=aaaaa.xls");
        this.init(list, sheetName, title, Type.EXPORT);
        //exportExcel(response);
        exportExcelOutputStream(response);
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param sheetName 工作表的名称
     */
    public void importTemplateExcel(HttpServletResponse response, List<String> sheetName) {
        List<String> lists = new ArrayList<>();
        importTemplateExcel(response, sheetName, lists);
    }

    /***
     * 將Excel倒出到指定位置
     * **/
    public void exportExcel(List<List<? extends Object>> list, List<String> sheetName, List<String> title, String path) {
        this.init(list, sheetName, title, Type.EXPORT);
        exportExcel(path);
    }

    /***
     * 將Excel倒出到指定位置
     * **/
    public void exportExcelMap(List<List<?>> list, List<String> head, List<String> sheetName, List<String> title, String path) {
        this.init(list, sheetName, title, Type.EXPORT);
        exportExcelMap(path);
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param sheetName 工作表的名称
     * @param title     标题
     * @return 结果
     */
    public void importTemplateExcel(HttpServletResponse response, List<String> sheetName, List<String> title) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        this.init(null, sheetName, title, Type.IMPORT);
        exportExcel(response);
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @return 结果
     */
    public void exportExcel(HttpServletResponse response) {
        try {
            writeSheet();
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(workbook);
        }
    }

    public void exportExcelOutputStream(HttpServletResponse response) {
        try (OutputStream outputStream = response.getOutputStream()) {
            writeSheet();
            workbook.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("输出错误信息，", e);
        } finally {
            IOUtils.closeQuietly(workbook);
        }


    }

    /**
     * 倒出Excel到指定位置
     **/
    public void exportExcel(String exportPath) {
        try {
            writeSheet();
            FileOutputStream fileOutputStream = new FileOutputStream(exportPath);
            workbook.write(fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(workbook);
        }
    }

    public void exportExcelMap(String exportPath) {
        try {
            writeSheetMap();
            FileOutputStream fileOutputStream = new FileOutputStream(exportPath);
            workbook.write(fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
        } finally {
            IOUtils.closeQuietly(workbook);
        }
    }

    /**
     * 创建写入数据到Sheet
     */
    public void writeSheet() {
        for (int i = 0; i < sheetName.size(); i++) {
            // 取出一共有多少个sheet.
            int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
            for (int index = 0; index < sheetNo; index++) {
                createSheet(sheetNo, index);

                // 产生一行
                Row row = sheet.get(i).createRow(rowNum);
                int column = 0;
                // 写入各个字段的列头名称
                for (Object[] os : fields.get(i)) {
                    Field field = (Field) os[0];
                    Excel excel = (Excel) os[1];
                    if (Collection.class.isAssignableFrom(field.getType())) {
                        for (Field subField : subFields.get(i)) {
                            Excel subExcel = subField.getAnnotation(Excel.class);
                            this.createHeadCell(subExcel, row, column++);
                        }
                    } else {
                        this.createHeadCell(excel, row, column++);
                    }

                }

                if (Type.EXPORT.equals(type)) {
                    fillExcelData(index, row);
                    addStatisticsRow();
                }
            }
        }

    }

    /**
     * 创建写入数据到Sheet
     */
    public void writeSheetMap() {
        for (int i = 0; i < sheetName.size(); i++) {
            // 取出一共有多少个sheet.
            int sheetNo = Math.max(1, (int) Math.ceil(list.size() * 1.0 / sheetSize));
            for (int index = 0; index < sheetNo; index++) {
                createSheet(sheetNo, index);

                // 产生一行
                Row row = sheet.get(i).createRow(rowNum);
                int column = 0;
                // 写入各个字段的列头名称
                for (Object[] os : fields.get(i)) {
                    Field field = (Field) os[0];
                    Excel excel = (Excel) os[1];
                    if (Collection.class.isAssignableFrom(field.getType())) {
                        for (Field subField : subFields.get(i)) {
                            Excel subExcel = subField.getAnnotation(Excel.class);
                            this.createHeadCell(subExcel, row, column++);
                        }
                    } else {
                        this.createHeadCell(excel, row, column++);
                    }

                }

                if (Type.EXPORT.equals(type)) {
                    fillExcelData(index, row);
                    addStatisticsRow();
                }
            }
        }

    }

    /**
     * 填充excel数据
     *
     * @param index 序号
     * @param row   单元格行
     */
    @SuppressWarnings("unchecked")
    public void fillExcelData(int index, Row row) {
        for (int k = 0; k < sheetName.size(); k++) {
            int startNo = index * sheetSize;
            int endNo = Math.min(startNo + sheetSize, list.get(k).size());
            int rowNo = (1 + rowNum) - startNo;
            for (int i = startNo; i < endNo; i++) {
                rowNo = isSubList(k) ? (i > 1 ? rowNo + 1 : rowNo + i) : i + 1 + rowNum - startNo;
                row = sheet.get(k).createRow(rowNo);
                // 得到导出对象.
                T vo = (T) list.get(k).get(i);
                Collection<?> subList = null;
                if (isSubList(k)) {
                    if (isSubListValue(vo, k)) {
                        subList = getListCellValue(vo, k);
                        subMergedLastRowNum = subMergedLastRowNum + subList.size();
                    } else {
                        subMergedFirstRowNum++;
                        subMergedLastRowNum++;
                    }
                }
                int column = 0;
                for (Object[] os : fields.get(k)) {
                    Field field = (Field) os[0];
                    Excel excel = (Excel) os[1];
                    if (Collection.class.isAssignableFrom(field.getType()) && subList != null) {
                        boolean subFirst = false;
                        for (Object obj : subList) {
                            if (subFirst) {
                                rowNo++;
                                row = sheet.get(k).createRow(rowNo);
                            }
                            List<Field> subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class);
                            int subIndex = 0;
                            for (Field subField : subFields) {
                                if (subField.isAnnotationPresent(Excel.class)) {
                                    subField.setAccessible(true);
                                    Excel attr = subField.getAnnotation(Excel.class);
                                    this.addCell(attr, row, (T) obj, subField, column + subIndex);
                                }
                                subIndex++;
                            }
                            subFirst = true;
                        }
                        this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size();
                    } else {
                        this.addCell(excel, row, vo, field, column++);
                        this.addCell(excel, row, vo, field, column++);
                    }
                }
            }
        }

    }

    /**
     * 创建表格样式
     *
     * @param wb 工作薄对象
     * @return 样式列表
     */
    private List<Map<String, CellStyle>> createStyles(Workbook wb) {
        List<Map<String, CellStyle>> result = new ArrayList<>();
        for (int i = 0; i < clazz.size(); i++) {
            // 写入各条记录,每条记录对应excel表中的一行
            Map<String, CellStyle> styles = new HashMap<>();
            CellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            Font titleFont = wb.createFont();
            titleFont.setFontName("Arial");
            titleFont.setFontHeightInPoints((short) 16);
            titleFont.setBold(true);
            style.setFont(titleFont);
            styles.put("title", style);
            style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setBorderRight(BorderStyle.THIN);
            style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setBorderLeft(BorderStyle.THIN);
            style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setBorderTop(BorderStyle.THIN);
            style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            style.setBorderBottom(BorderStyle.THIN);
            style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
            Font dataFont = wb.createFont();
            dataFont.setFontName("Arial");
            dataFont.setFontHeightInPoints((short) 10);
            style.setFont(dataFont);
            styles.put("data", style);
            style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            Font totalFont = wb.createFont();
            totalFont.setFontName("Arial");
            totalFont.setFontHeightInPoints((short) 10);
            style.setFont(totalFont);
            styles.put("total", style);
            styles.putAll(PoiHandler.annotationHeaderStyles(wb, styles, fields.get(i)));
            styles.putAll(PoiHandler.annotationDataStyles(wb, fields.get(i)));
            result.add(styles);
        }

        return result;
    }

    /**
     * 创建单元格
     */
    public void createHeadCell(Excel attr, Row row, int column) {
        for (int i = 0; i < sheet.size(); i++) {
            // 创建列
            Cell cell = row.createCell(column);
            // 写入列信息
            cell.setCellValue(attr.name());
            setDataValidation(attr, row, column);
            cell.setCellStyle(styles.get(i).get(StrUtil.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor())));
            if (isSubList(i)) {
                sheet.get(i).setDefaultColumnStyle(column, styles.get(i).get(StrUtil.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
                if (attr.needMerge()) {
                    sheet.get(i).addMergedRegion(new CellRangeAddress(rowNum - 1, rowNum, column, column));
                }
            }
        }

    }

    /**
     * 设置单元格信息
     *
     * @param value 单元格值
     * @param attr  注解相关
     * @param cell  单元格信息
     */
    public void setCellVo(Object value, Excel attr, Cell cell) {
        if (Excel.ColumnType.STRING == attr.cellType()) {
            String cellValue = Convert.toStr(value);
            // 对于任何以表达式触发字符 =-+@开头的单元格，直接使用tab字符作为前缀，防止CSV注入。
            if (StringUtils.startsWithAny(cellValue, FORMULA_STR)) {
                cellValue = RegExUtils.replaceFirst(cellValue, FORMULA_REGEX_STR, "\t$0");
            }
            cell.setCellValue(cellValue == null ? attr.defaultValue() : cellValue + attr.suffix());
        } else if (Excel.ColumnType.NUMERIC == attr.cellType()) {
            if (value != null) {
                cell.setCellValue(StrUtil.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value));
            }
        } else if (Excel.ColumnType.IMAGE == attr.cellType()) {
            ClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 0, (short) cell.getColumnIndex(), cell.getRow().getRowNum(), (short) (cell.getColumnIndex() + 1), cell.getRow().getRowNum() + 1);
            String imagePath = Convert.toStr(value);
            if (StrUtil.isNotEmpty(imagePath)) {
//                byte[] data = ImageUtils.getImage(imagePath);
//                getDrawingPatriarch(cell.getSheet()).createPicture(anchor,
//                        cell.getSheet().getWorkbook().addPicture(data, getImageType(data)));
            }
        }
    }

    /**
     * 获取画布
     */
    public static Drawing<?> getDrawingPatriarch(Sheet sheet) {
        if (sheet.getDrawingPatriarch() == null) {
            sheet.createDrawingPatriarch();
        }
        return sheet.getDrawingPatriarch();
    }


    /**
     * 创建表格样式
     */
    public void setDataValidation(Excel attr, Row row, int column) {
        for (Sheet sheet1 : sheet) {
            // 设置列宽
            sheet1.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256));
            if (StrUtil.isNotEmpty(attr.prompt()) || attr.combo().length > 0) {
                // 提示信息或只能选择不能输入的列内容.
                PoiHandler.setPromptOrValidation(sheet1, attr.combo(), attr.prompt(), 1, 100, column, column);
            }
        }

    }

    /**
     * 添加单元格
     */
    public void addCell(Excel attr, Row row, T vo, Field field, int column) {
        Cell cell;
        for (int i = 0; i < sheet.size(); i++) {
            try {
                // 设置行高
                row.setHeight(maxHeight.get(i));
                if (attr.isExport()) {
                    cell = row.createCell(column);
                    if (isSubListValue(vo, i) && getListCellValue(vo, i).size() > 1 && attr.needMerge()) {
                        CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column);
                        sheet.get(i).addMergedRegion(cellAddress);
                    }
                    cell.setCellStyle(styles.get(i).get(StrUtil.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor())));
                    Object value = getTargetValue(vo, field, attr);
                    String dateFormat = attr.dateFormat();
                    String readConverterExp = attr.readConverterExp();
                    String separator = attr.separator();
                    if (StrUtil.isNotEmpty(dateFormat) && value != null) {
                        cell.setCellValue(parseDateToStr(dateFormat, value));
                    } else if (StrUtil.isNotEmpty(readConverterExp) && value != null) {
                        cell.setCellValue(PoiHandler.convertByExp(Convert.toStr(value), readConverterExp, separator));
                    } else if (value instanceof BigDecimal && -1 != attr.scale()) {
                        cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).doubleValue());
                    } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) {
                        cell.setCellValue(PoiHandler.dataFormatHandlerAdapter(value, attr, cell, workbook));
                    } else {
                        // 设置列类型
                        setCellVo(value, attr, cell);
                    }
                    addStatisticsData(column, Convert.toStr(value), attr);
                }
            } catch (Exception e) {
                log.error("导出Excel失败", e);
            }
        }

    }


    public void setPromptOrValidation(Sheet sheet, String[] textList, String promptContent, int firstRow, int endRow,
                                      int firstCol, int endCol) {
        DataValidationHelper helper = sheet.getDataValidationHelper();
        DataValidationConstraint constraint = textList.length > 0 ? helper.createExplicitListConstraint(textList) : helper.createCustomConstraint("DD1");
        CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
        DataValidation dataValidation = helper.createValidation(constraint, regions);
        if (StrUtil.isNotEmpty(promptContent)) {
            dataValidation.createPromptBox("", promptContent);
            dataValidation.setShowPromptBox(true);
        }
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }
        sheet.addValidationData(dataValidation);
    }

    /**
     * 创建统计行
     */
    public void addStatisticsRow() {
        for (int i = 0; i < sheet.size(); i++) {
            if (!statistics.isEmpty()) {
                Row row = sheet.get(i).createRow(sheet.get(i).getLastRowNum() + 1);
                Set<Integer> keys = statistics.keySet();
                Cell cell = row.createCell(0);
                cell.setCellStyle(styles.get(i).get("total"));
                cell.setCellValue("合计");

                for (Integer key : keys) {
                    cell = row.createCell(key);
                    cell.setCellStyle(styles.get(i).get("total"));
                    cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key)));
                }
                statistics.clear();
            }
        }

    }


    /**
     * 获取bean中的属性值
     *
     * @param vo    实体对象
     * @param field 字段
     * @param excel 注解
     * @return 最终的属性值
     * @throws Exception
     */
    private Object getTargetValue(T vo, Field field, Excel excel) throws Exception {
        Object o = field.get(vo);
        if (StrUtil.isNotEmpty(excel.targetAttr())) {
            String target = excel.targetAttr();
            if (target.contains(".")) {
                String[] targets = target.split("[.]");
                for (String name : targets) {
                    o = getValue(o, name);
                }
            } else {
                o = getValue(o, target);
            }
        }
        return o;
    }

    /**
     * 以类的属性的get方法方法形式获取值
     *
     * @param o    反射类
     * @param name 键值
     * @return value
     * @throws Exception
     */
    private Object getValue(Object o, String name) throws Exception {
        if (o != null && StrUtil.isNotEmpty(name)) {
            Class<?> clazz = o.getClass();
            Field field = clazz.getDeclaredField(name);
            field.setAccessible(true);
            o = field.get(o);
        }
        return o;
    }


    /**
     * 获取字段注解信息
     */
    public List<List<Object[]>> getFields() {
        List<List<Object[]>> fields = new ArrayList<>();
        for (int i = 0; i < clazz.size(); i++) {
            List<Field> tempFields = new ArrayList<>();
            tempFields.addAll(Arrays.asList(clazz.get(i).getSuperclass().getDeclaredFields()));
            tempFields.addAll(Arrays.asList(clazz.get(i).getDeclaredFields()));
            List<Object[]> rows = new ArrayList<>();
            for (Field field : tempFields) {
                if (!ArrayUtils.contains(this.excludeFields, field.getName())) {
                    // 单注解
                    if (field.isAnnotationPresent(Excel.class)) {
                        Excel attr = field.getAnnotation(Excel.class);

                        if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
                            field.setAccessible(true);
                            Object[] objects = {field, attr};
                            rows.add(objects);
                        }
                        if (Collection.class.isAssignableFrom(field.getType())) {
                            subMethod.add(getSubMethod(field.getName(), clazz.get(i)));
                            ParameterizedType pt = (ParameterizedType) field.getGenericType();
                            Class<?> subClass = (Class<?>) pt.getActualTypeArguments()[0];
                            subFields.add(FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class));
                        }

                    }

                    // 多注解
                    if (field.isAnnotationPresent(Excels.class)) {
                        Excels attrs = field.getAnnotation(Excels.class);
                        Excel[] excels = attrs.value();
                        for (Excel attr : excels) {
                            if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) {
                                field.setAccessible(true);
                                Object[] objects = {field, attr};
                                rows.add(objects);
                                fields.add(rows);
                            }
                        }
                    }

                }
            }
            fields.add(rows);
        }

        return fields;
    }

    /**
     * 根据注解获取最大行高
     */


    public List<Short> getRowHeight() {
        double maxHeight = 0;
        List<Short> result = new ArrayList<>();
        for (int i = 0; i < fields.size(); i++) {
            for (Object[] os : this.fields.get(i)) {
                Excel excel = (Excel) os[1];
                maxHeight = Math.max(maxHeight, excel.height());
            }
            result.add((short) (maxHeight * 20));
        }
        return result;
    }


    /**
     * 创建工作表
     *
     * @param sheetNo sheet数量
     * @param index   序号
     */
    public void createSheet(int sheetNo, int index) {
        for (int i = 0; i < sheetName.size(); i++) {
            if (sheetNo > 1 && index > 0) {
                sheet.add(workbook.createSheet());
                this.createTitle();
                workbook.setSheetName(index, sheetName.get(i) + index);
            }
        }

    }


    /**
     * 判断空行
     *
     * @param row 判断的行
     */
    private boolean isRowEmpty(Row row) {
        if (row == null) {
            return true;
        }
        for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
            Cell cell = row.getCell(i);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }

    /**
     * 格式化不同类型的日期对象
     *
     * @param dateFormat 日期格式
     * @param val        被格式化的日期对象
     * @return 格式化后的日期字符
     */
    public String parseDateToStr(String dateFormat, Object val) {
        if (val == null) {
            return "";
        }
        String str;
        if (val instanceof Date) {
            str = new SimpleDateFormat(dateFormat).format((Date) val);
        } else if (val instanceof LocalDateTime) {
            str = new SimpleDateFormat(dateFormat).format(val);
        } else if (val instanceof LocalDate) {
            str = new SimpleDateFormat(dateFormat).format(val);
            ;
        } else {
            str = val.toString();
        }
        return str;
    }

    /**
     * 判断是否有对象的子列表
     */
    public boolean isSubList(int i) {
        return !subFields.get(i).isEmpty();
    }

    /**
     * 判断是否有对象的子列表值
     */
    public boolean isSubListValue(T vo, int i) {
        return !subFields.get(i).isEmpty() && getListCellValue(vo, i) != null && !getListCellValue(vo, i).isEmpty();
    }

    /**
     * 获取集合的值
     */
    public Collection<?> getListCellValue(Object obj, int i) {
        Object value = null;
        try {
            value = subMethod.get(i).invoke(obj, new Object[]{});
        } catch (Exception e) {
            return new ArrayList<Object>();
        }
        return (Collection<?>) value;
    }

    /**
     * 获取对象的子列表方法
     *
     * @param name      名称
     * @param pojoClass 类对象
     * @return 子列表方法
     */
    public Method getSubMethod(String name, Class<?> pojoClass) {
        StringBuilder getMethodName = new StringBuilder("get");
        getMethodName.append(name.substring(0, 1).toUpperCase());
        getMethodName.append(name.substring(1));
        Method method = null;
        try {
            method = pojoClass.getMethod(getMethodName.toString(), new Class[]{});
        } catch (Exception e) {
            log.error("获取对象异常", e);
        }
        return method;
    }

    /**
     * 获取单元格值
     *
     * @param row    获取的行
     * @param column 获取单元格列号
     * @return 单元格值
     */
    public Object getCellValue(Row row, int column) {
        if (row == null) {
            return null;
        }
        Object value = "";
        try {
            Cell cell = row.getCell(column);
            if (cell != null) {
                if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
                    value = cell.getNumericCellValue();
                    if (DateUtil.isCellDateFormatted(cell)) {
                        value = DateUtil.getJavaDate((Double) value); // POI Excel 日期格式转换
                    } else {
                        if ((Double) value % 1 != 0) {
                            value = new BigDecimal(value.toString());
                        } else {
                            value = new DecimalFormat("0").format(value);
                        }
                    }
                } else if (cell.getCellType() == CellType.STRING) {
                    value = cell.getStringCellValue();
                } else if (cell.getCellType() == CellType.BOOLEAN) {
                    value = cell.getBooleanCellValue();
                } else if (cell.getCellType() == CellType.ERROR) {
                    value = cell.getErrorCellValue();
                }

            }
        } catch (Exception e) {
            log.error("获取Cell的值错误:", e);
            return value;
        }
        return value;
    }
    /**
     * 获取图片类型,设置图片插入类型
     */
//    public int getImageType(byte[] value) {
//        String type = FileTypeUtils.getFileExtendName(value);
//        if ("JPG".equalsIgnoreCase(type)) {
//            return Workbook.PICTURE_TYPE_JPEG;
//        } else if ("PNG".equalsIgnoreCase(type)) {
//            return Workbook.PICTURE_TYPE_PNG;
//        }
//        return Workbook.PICTURE_TYPE_JPEG;
//    }

    /***
     * 根据读取的Excel语句
     * **/
    public List<CreateTablesBO> getDDL(Workbook workbook) throws IOException {
        // 如果指定sheet名,循环变脸sheet

        Sheet sheet = null;
        int numberOfSheets = workbook.getNumberOfSheets();
        //读取所有sheet页的表头
        List<CreateTablesBO> createList = new ArrayList<>();
        for (int j = 0; j < numberOfSheets; j++) {
            CreateTablesBO createTablesBO = new CreateTablesBO();
            sheet = workbook.getSheetAt(j);
            int rows = sheet.getLastRowNum();
            if (rows > 0) {
                //获取表行 head头
                List<ColumsBO> columsList = new ArrayList<>();
                Row head = sheet.getRow(1);
                for (int i = 0; i < head.getPhysicalNumberOfCells(); i++) {
                    Cell cell = head.getCell(i);
                    ColumsBO columsBO = new ColumsBO();
                    if (cell != null) {
                        String value = getCellValue(head, i).toString();
                        String convert = BeanUtils.getPinYin(value);
                        columsBO.setColumName(convert);
                        columsBO.setColumDescription(value);
                    }
                    columsList.add(columsBO);
                }
                String englishSheetName = BeanUtils.getPinYin(sheet.getSheetName());
                createTablesBO.setTableName(englishSheetName);
                createTablesBO.setColumns(columsList);
            }
            createTablesBO.setTableDescription(sheet.getSheetName());
            createList.add(createTablesBO);

        }
        return createList;
    }

}
